Imports System.Data.DataColumn
Imports System.Data
Imports CapaDeNegocios

Partial Public Class FrmRemitoCompra
    Inherits System.Web.UI.Page

    Public Concepto As CapaDeNegocios.nConcepto = New CapaDeNegocios.nConcepto
    Public Remito As CapaDeNegocios.nRemito = New CapaDeNegocios.nRemito
    Public Detalle As CapaDeNegocios.nDetalleRemitoCompra = New CapaDeNegocios.nDetalleRemitoCompra
    Public Comprobaciones As CapaDeNegocios.nComprobaciones = New CapaDeNegocios.nComprobaciones
    Public Proveedor As CapaDeNegocios.nProveedor = New CapaDeNegocios.nProveedor
   
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("Login") = "Anonimo" Then
            Response.Redirect("/")
        End If
        If Not Page.IsPostBack Then
            LLenarComboConceptos()
            TxtSucursal.Focus()
            LblError.Visible = False
            TxtCalendario.SelectedDate = Date.Today()
            LinkBuscarConcepto.OnClientClick = "javascript:var popup = window.open('FrmListadoProveedor.aspx?ID=" + HFProveedor.ClientID + "&Descripcion=" + TxtProveedor.ClientID + "','popup','Width=700,Height=500,Scrollbars=NO,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO')"
            LinkRemitos.OnClientClick = "javascript:window.open('FrmListadoRemitoCompra.aspx?ID=" + HFRemito.ClientID + "&idboton=" + BtnRefrescar.ClientID + "','popupdos','Width=730,Height=600,Scrollbars=yes,Resizable=NO,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO');"
            LinkGuardar.Enabled = False
        End If

    End Sub
    Sub LLenarComboConceptos()
        CboConcepto.Items.Clear()
        CboConcepto.Items.Add(New ListItem("Seleccione un concepto", -1))
        CboConcepto.DataSource = Concepto.ListarConcepto(0, "", "", 0, "Compra")
        CboConcepto.DataTextField = "Descripcion"
        CboConcepto.DataValueField = "CodigoConcepto"
        CboConcepto.DataBind()

    End Sub

    Protected Sub LinkAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkAgregar.Click
        If HFProveedor.Value <> "" Then
            TxtProveedor.Text = ""
            TxtProveedor.Text = Proveedor.DarRazonSocial(HFProveedor.Value)
        End If
        Dim Cont As Integer
        Cont = 0
        LblError.Text = ""
        LblError.Visible = False
        If CboConcepto.SelectedIndex <> -1 And CboConcepto.SelectedIndex > 0 Then
            CboConcepto.Items(CboConcepto.SelectedIndex).Enabled = False
        End If
        If CboConcepto.SelectedItem.Text = "" Then
            LblError.Text = LblError.Text + "-Error,no hay mas conceptos"
            Cont = Cont + 1
        End If
       
        If CboConcepto.SelectedValue.ToString() = -1 Then
            LblError.Text = "Error,El Concepto seleccionado no es Valido"
            Cont = Cont + 1
        End If
        If Not IsNumeric(TxtCantidad.Text) Then
            LblError.Text = LblError.Text & "/Error, La cantidad debe ser numero"
            Cont = Cont + 1
        Else
            If TxtCantidad.Text = 0 Then
                LblError.Text = LblError.Text & "/Error, La cantidad debe ser mayor a cero"
                Cont = Cont + 1
            End If
        End If
        If Cont = 0 Then
            Dim dt As New DataTable
            Dim dr As DataRow
            Try
                If Me.ViewState("Detalle") Is Nothing Then
                    dt.Columns.Add(New DataColumn("CodigoConcepto", GetType(String)))
                    dt.Columns.Add(New DataColumn("Descripcion", GetType(String)))
                    dt.Columns.Add(New DataColumn("Cantidad", GetType(String)))
                Else
                    dt = Me.ViewState("Detalle")
                End If
                dr = dt.NewRow()
                dr("CodigoConcepto") = CboConcepto.SelectedValue.ToString()
                dr("Descripcion") = CboConcepto.SelectedItem.Text
                dr("Cantidad") = TxtCantidad.Text
                dt.Rows.Add(dr)
                Me.ViewState.Add("Detalle", dt)
                GridConcepto.DataSource = dt.DefaultView
                GridConcepto.DataBind()
                HfCuenta.Value = CInt(TxtCantidad.Text)

            Catch ex As Exception
                LblError.Text = ex.ToString
            End Try
            Dim Total As Integer
            If TxtTotal.Text = "" Then
                TxtTotal.Text = 0
            Else
                Total = TxtTotal.Text
            End If
            TxtTotal.Text = CInt((HfCuenta.Value) + Total)
            If HFProveedor.Value <> "" Then
                TxtProveedor.Text = ""
                TxtProveedor.Text = Proveedor.DarRazonSocial(HFProveedor.Value)
            End If
        Else
            LblError.Visible = True
        End If

        LinkGuardar.Enabled = True
        If HFProveedor.Value <> "" Then
            TxtProveedor.Text = ""
            TxtProveedor.Text = Proveedor.DarRazonSocial(HFProveedor.Value)
        End If

    End Sub
    Sub LimpiarFormulario()
        TxtSucursal.ReadOnly = False
        TxtNumero.ReadOnly = False
        TxtCantidad.Text = ""
        TxtTotal.Text = ""
        TxtNumero.Text = ""
        CboConcepto.Enabled = True
        TxtSucursal.Text = ""
        TxtNumero.Text = "00000000"
        TxtSucursal.Text = "0000"
        CboCondicion.SelectedIndex = -1
        CboConcepto.SelectedIndex = -1
        LblError.Visible = False
        HFProveedor.Value = ""
        TxtProveedor.Text = ""
        TxtObservacion.Text = ""
        Me.ViewState.Clear()
        LLenarComboConceptos()
        GridConcepto.DataBind()
    End Sub
    Sub BorrarDataset(ByVal dts As DataSet)
        If dts.Tables(0).Rows.Count() > 0 Then
            dts.Tables(0).Rows.Remove(dts.Tables(0).Rows(0))
            BorrarDataset(dts)
        End If
    End Sub
    Protected Sub LinkGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkGuardar.Click
        Dim VarRemito As Integer
        Dim Cont As Integer
        Dim i As Integer
        Dim ceros As Integer
        LblError.Visible = False
        LblError.Text = ""
        Cont = 0

        If Comprobaciones.FN_CantCaracteres(TxtNumero.Text, 8) = False Then
            ceros = Int(8 - Len(TxtNumero.Text))
            For i = 0 To ceros - 1
                TxtNumero.Text = "0" + TxtNumero.Text
            Next

        End If

        If Comprobaciones.FN_CantCaracteres(TxtSucursal.Text, 4) = False Then
            ceros = Int(4 - Len(TxtNumero.Text))
            For i = 0 To ceros - 1
                TxtNumero.Text = "0" + TxtNumero.Text
            Next
        End If

        If CboCondicion.SelectedValue.ToString = -1 Then
            LblError.Text = LblError.Text & "- Error,la Condicion de Compra no es Correcta"
            Cont = Cont + 1
        End If
        If HFProveedor.Value = "" Then
            Me.Response.Write("<script languaje='javascript'>window.alert('Error, No hay Proveedor Seleccionado')</script>")
        End If

        If Cont = 0 Then
            Dim VarNumRemito As String = ""
            VarNumRemito = ("X" & TxtSucursal.Text & "-" & TxtNumero.Text)
            If Not Remito.ExisteRemito(VarNumRemito, HFProveedor.Value) Then
                VarRemito = Remito.InsertarRemito(TxtCalendario.Text, Trim(VarNumRemito), _
                Int(HFProveedor.Value), Int(TxtCantidad.Text), "Pendiente", Trim(TxtObservacion.Text), CboCondicion.SelectedValue.ToString())
                If Int(VarRemito) > 0 Then
                    For i = 0 To Me.ViewState("Detalle").rows.Count - 1
                        Detalle.InsertarDetalle(TxtCalendario.Text, Int(Me.ViewState("Detalle").rows(i)("Cantidad").ToString()), Int(Me.ViewState("Detalle").rows(i)("CodigoConcepto").ToString()), VarRemito)
                    Next

                    Me.Response.Write("<script languaje='javascript'>window.alert('El Alta del Remito fue Correcta')</script>")
                    LimpiarFormulario()
                End If
            Else
                LblError.Text = "Error, el remito ya fue Ingresado."
                LblError.Visible = True
                TxtSucursal.Focus()
            End If
        Else
            LblError.Visible = True
            Cont = 0
        End If

    End Sub

    Protected Sub LinkCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkCancelar.Click
        LimpiarFormulario()
    End Sub

    Protected Sub GridConcepto_RowCommand(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridConcepto.RowCommand

        If e.CommandName = "Eliminar" Then
            LblError.Text = ""
            LblError.Visible = False
            Dim dt As New DataTable

            Try
                If Me.ViewState("Detalle") Is Nothing Then
                    LblError.Text = "No se puede eliminar no hay nada en la grilla"
                Else
                    dt = Me.ViewState("Detalle")
                End If
                TxtTotal.Text = Int(TxtTotal.Text) - Int(e.CommandSource.parent.FindControl("Lblcantidad").text)

                dt.Rows.RemoveAt(e.CommandSource.parent.parent.rowindex)
                'dt.Rows.Remove(e.CommandSource.parent.parent.rowindex)

                GridConcepto.DataSource = dt.DefaultView
                GridConcepto.DataBind()
                ' HfCuenta.Value = (CInt(TxtCantidad.Text) * -1)
                If CboConcepto.SelectedIndex = 0 Then CboConcepto.Enabled = True
                CboConcepto.DataSource = Concepto.ListarConcepto(Int(e.CommandSource.Parent.Parent.FindControl("HFCodigo").value.ToString()), "", "", 0, "Compra")
                CboConcepto.DataTextField = "Descripcion"
                CboConcepto.DataValueField = "CodigoConcepto"
                CboConcepto.DataBind()
                'CboConcepto.SelectedValue = e.CommandSource.Parent.Parent.FindControl("HFCodigo").value.ToString()
                'CboConcepto.Items(CboConcepto.Items.IndexOf(CboConcepto.Items.FindByValue(CInt(e.CommandSource.Parent.Parent.FindControl("HFCodigo").value.ToString())))).Enabled = True
            Catch ex As Exception
                LblError.Text = ex.ToString
            End Try

        End If
    End Sub
    Protected Sub BtnRefrescar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnRefrescar.Click

    End Sub
    'Sub LlenarVentana()
    '    Dim Datos As New DataTable()
    '    Dim i As Integer

    '    If HFRemito.Value <> "" Then
    '        Datos = Remito.ListarRemitos(Int(HFRemito.Value), "", "", 0, 0, "", "", "").Tables(0)
    '        For i = 0 To Datos.Rows.Count - 1
    '            TxtFecha.Text = Datos.Rows(i)("Fecha").ToString()
    '            TxtProveedor.Text = Proveedor.DarRazonSocial(Datos.Rows(i)("CodigoProveedor").ToString())
    '            HFProveedor.Value = Datos.Rows(i)("CodigoProveedor").ToString()
    '            TxtSucursal.Text = (Datos.Rows(i)("Numero").ToString()).Substring(1, 5)
    '            TxtNumero.Text = (Datos.Rows(i)("Numero").ToString()).Substring(7, 8)
    '            CboCondicion.SelectedValue = Int(Datos.Rows(i)("CondicionCompra").ToString())
    '            TxtTotal.Text = Int(Datos.Rows(i)("Cantidad").ToString())
    '        Next

    '        GridConcepto.DataSource = Detalle.ListarTodo(0, "", 0, 0, Int(HFRemito.Value))
    '        Me.ViewState.Add("Detalle", Detalle.ListarTodo(0, "", 0, 0, Int(HFRemito.Value)).Tables(0))
    '        GridConcepto.DataBind()

    '        TxtSucursal.ReadOnly = True
    '        TxtNumero.ReadOnly = True
    '    End If
    'End Sub

    
    Protected Sub LinkNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkNuevo.Click
        LinkCancelar_Click(sender, e)
    End Sub

    Protected Sub CboCondicion_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CboCondicion.SelectedIndexChanged
        TxtNumero.Text = Replace(TxtNumero.ToString().PadLeft(8), " ", "0")
    End Sub
End Class